//
//  CZEmoticonCell.swift
//  007-表情键盘
//
//  Created by 名品导购网MPLife.com on 2017/12/15.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit
//表情cell协议
@objc protocol CZEmoticonCellDelegate:NSObjectProtocol {
    
    
    //表情cell选中表情模型
    ///
    /// - Parameter em: 表情模型/nil 表示删除
    func emoticonCellDidSelectedEmoticon(cell:CZEmoticonCell, em:CZEmoticon?)
}

//表情的页面cell 每一个页面显示20个cell
//每一个cell就是和collectionCell一样大小
//每一个cell中用九宫格算法 自行添加20个表情
//最后一个位置是删除按钮
class CZEmoticonCell: UICollectionViewCell {
    //代理不能用let
    weak var delegate:CZEmoticonCellDelegate?
    //当前页面表情数组 最多20个
    var emoticons:[CZEmoticon]? {
        didSet{
            //隐藏所有的按钮
            for v in contentView.subviews {
                v.isHidden = true
            }
            contentView.subviews.last?.isHidden = false
            //遍历表情模型数组  设置按钮图像
            for (i,em) in (emoticons ?? []).enumerated() {
                //取出按钮
                if let btn = contentView.subviews[i] as? UIButton{
                    
                    btn.setImage(em.image, for: .normal)
                    btn.setTitle(em.emoji, for: .normal)
                    btn.isHidden = false
                }
            }
        }
    }
    
    private lazy var tipView = CZEmoticonTipView()
    
    override func awakeFromNib() {
        self.contentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 258)
        setUPUI()
    }
    //当视图从界面上删除，同样会调用此方法newWindow = nil
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super .willMove(toWindow: newWindow)
        guard let w = newWindow else {
            return
        }
        
        //ios6.0之前
        //如果有地方就不要用窗口
        //将提示视图添加到窗口上
        w.addSubview(tipView)
        tipView.isHidden = true
    }
    //选中表情按钮
    @objc private func selectedEmoticonButton(button:UIButton){
        //取0~20 20 对应的是删除按钮
        let tag = button.tag
        //根据tag判断是否是删除按钮
        var em : CZEmoticon?
        if tag < (emoticons?.count) ?? 0 {
            em = emoticons?[tag]
            
        }
        //如果em为nil 对应的是删除按钮
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
        
    }
    //重要的手势  长按手势
    //可以保证 一个对象监听两种点击手势  而且不需要考虑解决手势冲突
    @objc private func longGesture(gesture:UILongPressGestureRecognizer){
        //测试添加提示视图
//        addSubview(tipView)
        //获取触摸的位置
        let location = gesture.location(in: self)
        
        //获取触摸位置对应的按钮
        guard let button = buttonWithLocation(loaction: location) else {
            tipView.isHidden  = true;
            return
        }
        //处理手势状态
        switch gesture.state {
        case .began,.changed:
            tipView.isHidden = false
            //坐标系转换 
            let center = self.convert(button.center, to: window)
            //提供视图位置
            tipView.center = center
            //设置提示表情模型
            guard let count = emoticons?.count else {
                return
            }
            if button.tag < count {
                tipView.emoticon = emoticons?[button.tag]
            }
        case.ended:
//        case .ended:
//            tipView.isHidden = true
//            print("1")
            //执行选中按钮的函数
            selectedEmoticonButton(button: button)
        case .cancelled,.failed:
            tipView.isHidden = true
        default:
            break
        }
    }
    
    private func buttonWithLocation(loaction:CGPoint)->UIButton?{
        //遍历contentView所有的子视图 ，如果子视图可见  同时location确认是按钮
        for btn in contentView.subviews {
            //删除按钮同意需要处理
            if btn.frame.contains(loaction) && !btn.isHidden && btn != contentView.subviews.last{
                return btn as? UIButton
            }
        }
        return nil
    }
}
private extension CZEmoticonCell{
    func setUPUI() {
        //连续创建21个按钮
        let rowCount = 3
        let colCount = 7
        let leftMargin:CGFloat = 8
        //底部间距为第分页预留
        let bottomMargin:CGFloat = 16
        let w = (self.contentView.frame.size.width-2*leftMargin) / CGFloat(colCount)
        let h = (self.contentView.frame.size.height-bottomMargin) / CGFloat(rowCount)
        
        for i in 0..<21 {
            
            let  row = i/colCount
            let col = i % colCount
            let btn = UIButton()
            let x = leftMargin + CGFloat(col) * w
            let y = CGFloat(row) * h
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            self.contentView.addSubview(btn)
            
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            //设置按钮的tag
            btn.tag = i
            btn .addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside)
        }
        
        //取出末尾删除按钮
        let removeButton = contentView.subviews.last as! UIButton
        //设置图像
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: CZEmoticonManager.shared.bundle, compatibleWith: nil)
        removeButton .setImage(image, for: .normal)
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        //长按时间间隔
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
    }
}




















